package com.kotlin.zds.glide

import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.FutureTarget
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.zds.support.gilde.ImageLoaderStrategy
import com.zds.support.util.LogUtils

import kotlin.concurrent.thread

/**
 *
 * @Description:Glide 图片加载管理器
 * @author zc
 * @version V1.0
 */
open class GlideImageLoader : ImageLoaderStrategy {
    override fun getBitmapSync(path: String): Bitmap {
        val future: FutureTarget<Bitmap> = with(context).asBitmap().load(path).submit()
        return future.get()
    }

    private lateinit var context: Context;


    override fun init(context: Context) {
        this.context = context
        Glide.getPhotoCacheDir(context)
    }

    override fun load(path: String) {
        thread {
            with(context).load(path)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
        }

    }

    override fun getBitmap(path: String, onGetBitmapListener: (bitmap: Bitmap) -> Unit) {
        with(context).asBitmap().load(path)
                .into(object : SimpleTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
                    override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                        onGetBitmapListener.invoke(resource)
                    }
                })
    }

    override fun cleanMemory(context: Context) {
    }

    override fun showImage(imageView: ImageView, path: String) {
        with(context).load(path).into(imageView)
    }

    /* override fun showImage(imageView: ImageView, path: String, imageLoaderOptions: ImageLoaderOptions) {
     }
 */
    override fun showImage(imageView: ImageView, path: String, placeholderResId: Int) {
        //FIXME transition(DrawableTransitionOptions().crossFade())
        // 第一次加载会显示失败的图片 https://github.com/bumptech/glide/issues/2024

        with(context).load(path)
                /*.transition(DrawableTransitionOptions().crossFade())*/
                .apply(RequestOptions().placeholder(placeholderResId).dontAnimate())
                .into(imageView)

    }

    override fun showImage(imageView: ImageView, path: String, placeholderResId: Int, failureResId: Int) {


        with(context).load(path)
                .apply(RequestOptions().placeholder(placeholderResId).error(failureResId).dontAnimate())
                .into(imageView)
    }

    override fun showImage(imageView: ImageView, path: String, placeholderResId: Int, failureResId: Int,
                           onSuccessListener: (path: String) -> Unit,
                           onFailListener: (e: Exception?) -> Unit) {


        with(context).load(path)
                .apply(RequestOptions().placeholder(placeholderResId).error(failureResId).dontAnimate())
                .listener(object : RequestListener<Drawable?> {
                    override fun onLoadFailed(e: GlideException?, model: Any?,
                                              target: Target<Drawable?>?,
                                              isFirstResource: Boolean): Boolean {
                        LogUtils.d("Glide", "加载图片失败")
                        onFailListener.invoke(e)
                        return false
                    }

                    override fun onResourceReady(resource: Drawable?,
                                                 model: Any?,
                                                 target: Target<Drawable?>?,
                                                 dataSource: DataSource?,
                                                 isFirstResource: Boolean): Boolean {

                        onSuccessListener.invoke(path)
                        return false
                    }
                })
                .into(imageView)
    }

    override fun showImage(imageView: ImageView, path: String, isGif: Boolean, placeholderResId: Int, failureResId: Int) {
        val requestManager = with(context)
        requestManager.clear(imageView)
        if (isGif) {
            requestManager
                    .asGif()
                    .load(path)/*.transition(DrawableTransitionOptions().crossFade())*/
                    .apply(RequestOptions().format(DecodeFormat.PREFER_ARGB_8888).placeholder(placeholderResId).error(failureResId))
                    .into(imageView)
        } else {
            requestManager
                    .load(path)
                    .apply(RequestOptions().placeholder(placeholderResId).error(failureResId).dontAnimate())
                    .into(imageView)
        }

    }

    open fun with(context: Context): RequestManager {
        // return Glide.with(context)
        return Glide.with(context)
    }

    override fun getDrawable(path: String, onGetDrawableListener: (drawable: Drawable) -> Unit) {

    }

    override fun showImageCorner(imageView: ImageView, path: String, placeholderResId: Int, failureResId: Int, cornerSize: Int) {
    }

    override fun clearMemory() {
        try {
            Glide.get(context).clearMemory()
        } catch (e: Exception) {

        }

    }

    override fun trimMemory(level: Int) {
        try {
            Glide.get(context).trimMemory(level)
        } catch (e: Exception) {
        }
    }

    override fun resumeRequests() {
        try {
            //恢复Glide加载图片
            Glide.with(context).resumeRequests()
        } catch (e: Exception) {
        }
    }

    override fun pauseRequests() {
        try {
            //恢复Glide加载图片
            Glide.with(context).pauseRequests();//禁止Glide加载图片
        } catch (e: Exception) {
        }
    }
}